package com.uw.uwrpc.core.util;

import com.uw.uwrpc.core.annotation.EnableUWReference;
import org.springframework.context.ApplicationContext;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class SpringPackageScanUtil {
    private SpringPackageScanUtil() {
    }

    public static List<Object> scan(ApplicationContext applicationContext, List<String> scanBasePathList) {
        List<Object> result = new ArrayList<>();
        String[] beanNames = applicationContext.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            Object bean = applicationContext.getBean(beanName);
            //启动扫描优化，跳过不在扫描路径的 Bean。
            if (!checkPath(bean, scanBasePathList)) {
                continue;
            }
            result.add(bean);
        }
        return result;
    }


    private static boolean checkPath(Object bean, List<String> scanBasePathList) {
        for (String scanBasePath : scanBasePathList) {
            if (bean.getClass().getPackageName().startsWith(scanBasePath)) {
                return true;
            }
        }
        return false;
    }


    public static List<String> getScanBasePath(ApplicationContext applicationContext) {
        List<String> scanBasePathList = new ArrayList<>();
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(EnableUWReference.class);
        for (Map.Entry<String, Object> entry : beansWithAnnotation.entrySet()) {
            Class<?> aClass = entry.getValue().getClass();
            if (aClass.isAnnotationPresent(EnableUWReference.class)) {
                EnableUWReference annotation = aClass.getAnnotation(EnableUWReference.class);
                scanBasePathList.addAll(Arrays.asList(annotation.scanBasePackages()));
            }
        }
        return scanBasePathList;
    }


}
